import React, { Component } from 'react';
import { Events } from '@tarojs/taro';
import { View, ScrollView } from '@tarojs/components'
import { AtFloatLayout, AtActivityIndicator } from 'taro-ui'
import IndexList from '../indexList'
import classnames from 'classnames'
import { fetchCarBrands, fetchCarSeries, fetchCarModel } from '@/api/car'
import './index.scss'
import { func } from 'prop-types'
type Prop = {
    isOpened: boolean
    model: any
    onChange: Function
    // onDelete: Function
}
type State = {
    mode: number
    currentTabIndx: number
    isOpened: boolean
    selector: Selector
    barndList: Array<any>
    seriesList: Array<any>
    modelList: Array<any>
};


type Selector = {
    ids: Array<number | string>,
    brand: CarSelectType,
    series: CarSelectType,
    model: CarSelectType,
    inputText: string
}

type CarSelectType = {
    id: any,
    text: string,
    jekunModelCode?: any
}
type tabValue = 0 | 1 | 2
export default class CarModel extends Component<Prop, State> {
    static options = {
        addGlobalClass: true,

    }
    // static propTypes = {
    //   onChange: PropTypes.func.isRequired
    // }
    constructor(props) {
        super(props)
        this.state = {
            mode: 1,
            currentTabIndx: 0,
            isOpened: true,
            barndList: [],
            seriesList: [],
            modelList: [],
            selector: {
                ids: [],
                brand: {
                    id: null,
                    text: ''
                },
                series: {
                    id: null,
                    text: ''
                },
                model: {
                    id: null,
                    jekunModelCode: null,
                    text: ''
                },
                inputText: '请选择车型'
            }
        }
    }
    UNSAFE_componentWillMount() {
        console.log('prop', this.props)
        const { model } = this.props

        if (model && model.ids.length === 1) {
            this.setState({
                selector: this.props.model,
                currentTabIndx: 1
            })
            this.getSeriesList(model.brand.id)
            // this.getModelList(this.props.model.series.id)
        }
        if (model && (model.ids.length === 2 || model.ids.length === 3)) {
            this.setState({
                selector: this.props.model,
                currentTabIndx: 2
            })
            this.getModelList(model.series.id)
            // this.getModelList(this.props.model.series.id)
        }

        if (!model || model.ids.length === 0) {
            this.getBrands()
        }
        // if (model && model.ids.length === 3) {
        //     this.setState({
        //         selector: this.props.model,
        //         currentTabIndx: 2
        //     })
        //     this.getModelList(model.series.id)
        // }

    }

    UNSAFE_componentWillReceiveProps(prevProps) {
        if (prevProps.isOpened !== this.state.isOpened) {
            this.setState({
                isOpened: prevProps.isOpened
            })
        }
        console.log('prop', this.props)
        if (prevProps.mode !== this.state.mode) {
            this.setState({
                mode: prevProps.mode
            })
        }
    }

    async getBrands() {
        try {
            let res: any = await fetchCarBrands()
            let data = res.data.data
            let filterData: any[] = []
            data.map((brand) => {
                if (brand.firstLetter) {
                    filterData.push({
                        title: brand.firstLetter,
                        key: brand.firstLetter,
                        items: filterItems(brand.items)
                    })
                }
            })

            function filterItems(brandItems: Array<any>) {
                brandItems = brandItems.map((item) => {
                    return {
                        ...item,
                        name: item.brandName
                    }
                })
                return brandItems
            }

            this.setState({
                barndList: filterData
            })
        } catch (error) {

        }
    }

    handleTabClick(value: tabValue) {
        const { barndList, seriesList, modelList, selector } = this.state
        if (value === 0 && barndList.length === 0) {
            this.getBrands()
        }
        if (value === 1 && seriesList.length === 0) {
            this.getSeriesList(parseInt(selector.brand.id))
        }
        if (value === 2 && modelList.length === 0) {
            this.getSeriesList(selector.series.id)
        }
        this.setState({
            currentTabIndx: value
        })
    }

    onBrandClick(item) {
        console.log('item', item)
        const { selector } = this.state
        if (selector.brand.id !== item.brandId) {

            let new_obj = Object.assign(selector, {
                brand: {
                    id: item.brandId,
                    text: item.brandName
                },
                series: {
                    id: null,
                    text: ''
                },
                model: {
                    id: null,
                    jekunModelCode: null,
                    text: ''
                },
                ids: [item.brandId],
                inputText: `${item.brandName} - `
            })
            this.setState({
                selector: new_obj,
                currentTabIndx: 1,
                seriesList: []
            }, () => {
                this.getSeriesList(item.brandId)
            })
        } else {
            this.setState({
                currentTabIndx: 1
            })
        }
    }

    async getSeriesList(id: number) {
        try {
            let res: any = await fetchCarSeries(id)
            let data = res.data.data
            this.setState({
                seriesList: data.list
            })
        } catch (error) {

        }
    }

    async getModelList(id: number) {
        try {
            let res: any = await fetchCarModel(id)
            let data = res.data.data
            this.setState({
                modelList: data
            })
        } catch (error) {

        }
    }

    handleSeriesClick(item) {
        const { selector } = this.state
        if (selector.series.id !== item.seriesId) {
            let ids = [selector.ids[0], item.seriesId]
            let new_obj = Object.assign(selector, {
                series: {
                    id: item.seriesId,
                    text: item.seriesName
                },
                model: {
                    id: null,
                    jekunModelCode: null,
                    text: ''
                },
                ids,
                inputText: `${selector.brand.text} - ${item.seriesName} -`
            })
            this.setState({
                selector: new_obj,
                currentTabIndx: 2,
                modelList: []
            }, () => {
                this.getModelList(item.seriesId)
            })
        } else {
            this.setState({
                currentTabIndx: 2
            })
        }
    }
    handleModelClick(item) {
        const { selector } = this.state

        let ids = [selector.ids[0], selector.ids[1], item.modelId]
        let new_obj = Object.assign(selector, {
            model: {
                id: item.modelId,
                jekunModelCode: item.jekunModelCode,
                text: item.modelName
            },
            ids,
            inputText: `${selector.brand.text} - ${selector.series.text} - ${item.modelName}`
        })
        console.log('test', new_obj)
        this.setState({
            selector: new_obj,
            isOpened: false
        }, () => {
            this.submitSelector()
        })
        // this.getSeriesList()
    }
    submitSelector() {
        this.props.onChange(this.state.selector);
    }
    isBrandView() {
        const { barndList, selector } = this.state
        return (
            <View className='brand'>
                { !barndList.length && <AtActivityIndicator mode='center'></AtActivityIndicator> }
                <IndexList list={barndList}
                    activeMenuItemId={selector.brand.id}
                    onClick={this.onBrandClick.bind(this)}>
                </IndexList>
            </View>
        )
    }
    isSeriesView() {
        const { seriesList, selector } = this.state
        console.log('selectorselectorselector', selector)
        return (
            <ScrollView
                className='series'
                scrollY
                scrollWithAnimation
            >
                { !seriesList.length && <AtActivityIndicator mode='center'></AtActivityIndicator> }
                <View className='series-wrap'>
                    {seriesList.map((list) =>
                        <View key={list.producerId} className="list-wrap">
                            <View className='title'>{list.producerName}</View>
                            <View className='items-wrap'>
                                {list.items.map((item) =>
                                    <View key={item.seriesId}
                                        onClick={this.handleSeriesClick.bind(this, item)}
                                        className={
                                            classnames('item', {
                                                'active': parseInt(item.seriesId) === parseInt(selector.series.id)
                                            })
                                        }>
                                        {item.seriesName}
                                    </View>
                                )}
                            </View>
                        </View>
                    )}
                </View>
            </ScrollView>
        )
    }
    isModelView() {
        const { modelList, selector } = this.state
        return (
            <ScrollView
                className='model'
                scrollY
                scrollWithAnimation
            >
                { !modelList.length && <AtActivityIndicator mode='center'></AtActivityIndicator> }
                <View className='model-wrap'>
                    {modelList.map((list) =>
                        <View key={list.years} className="list-wrap">
                            <View className='title'>{list.years}</View>
                            <View className='items-wrap'>
                                {list.items.map((item) =>
                                    <View key={item.modelId}
                                        onClick={this.handleModelClick.bind(this, item)}
                                        className={
                                            classnames('item', {
                                                'active': parseInt(item.modelId) === parseInt(selector.model.id)
                                            })
                                        }>
                                        {item.modelName}
                                    </View>
                                )}
                            </View>
                        </View>
                    )}
                </View>
            </ScrollView>
        )
    }
    render() {
        const { isOpened, currentTabIndx, selector } = this.state
        const { brand, series, model } = selector

        return (
            <View className='car-model'>
                <AtFloatLayout
                    isOpened={isOpened}
                    onClose={this.submitSelector.bind(this)}
                >
                    <View className="head-info">
                        <View className="title">
                            请选择车型
                        </View>

                        <View className="tab-wrap flex-row">
                            <View className={
                                classnames('item', {
                                    'active': currentTabIndx === 0
                                })}
                                onClick={this.handleTabClick.bind(this, 0)}
                            >品牌</View>

                            {brand.id && <View className={
                                classnames('item', {
                                    'active': currentTabIndx === 1
                                })}
                                onClick={this.handleTabClick.bind(this, 1)}
                            >车系</View>
                            }
                            {series.id && <View className={
                                classnames('item', {
                                    'active': currentTabIndx === 2
                                })}
                                onClick={this.handleTabClick.bind(this, 2)}
                            >车型</View>
                            }
                        </View>
                        <View className='selector'>
                            {selector.inputText}
                        </View>
                    </View>
                    {
                        {
                            0: this.isBrandView(),
                            1: this.isSeriesView(),
                            2: this.isModelView()
                        }[currentTabIndx]
                    }
                </AtFloatLayout>
            </View>

        )
    }
}
